import { reports } from '@/api/modules/reports'
import { pay } from '@/api/modules/pay'
import { get, filter, find } from 'lodash'
import { getCharge } from '@/components/storybook/utilties/chargebee'
import { getResourceNum } from '@/components/storybook/utilties/tools'

export const handleData = async (onlyData) => {
  const { getAppsMarketListApi } = reports
  const { data: res } = await getAppsMarketListApi()
  const data = res.data.map(item => {
    item.getCharge = getCharge(item.chargebeeItemPricesList)
    if (item.getCharge.addon) {
      item.price = item.getCharge.addon[0]
    } else if (item.getCharge.plan) {
      item.price = item.getCharge.plan[0]
    } else {
      item.price = 0
    }
    item.getChargeYear = getCharge(item.chargebeeItemPricesList, 'year')
    if (item.getChargeYear.addon) {
      item.priceYear = item.getChargeYear.addon[0]
    } else if (item.getChargeYear.plan) {
      item.priceYear = item.getChargeYear.plan[0]
    } else {
      item.priceYear = 0
    }
    return item
  })
  if (onlyData) {
    return data
  }
  return {
    data,
    Bi: await handleBiPackage(data),
    Bot: await handleBot(data),
    App: await handleApps(data),
    Bundle: await handleBundle(data)
  }
}

export const handleBiPackage = async (data) => {
  const { getReportDataInfo } = reports
  const { rules } = pay
  const params = {
    gadgetId: '76c35523-5a44-42b6-875d-6b00215349e7',
    gadgettype: 'gridgadget',
    type: 'widget',
    code: 'TEAMS'
  }
  let biPackageList = filter(data, { type: 2 })
  const ids = biPackageList.filter(i => i.type === 2).map(i => i.appId).join(',')
  const [{ data: data1 }, { data: data2 }] = await Promise.all([getReportDataInfo(params), rules({ ids })])
  const reportInfo = data1
  const rule = data2
  biPackageList = biPackageList.map(item => {
    const ruleObject = rule.data.find(i => i.appId === item.appId && i.type === 13)
    const code = get(ruleObject, 'threshold.value')
    const resoures = reportInfo.data.find(i => i.dimension1 === code)
    item.configCode = code
    if (resoures) {
      item.resourceNum = getResourceNum(resoures)
    }
    return item
  })
  return filter(biPackageList, item => { 
     return item.resourceNum && item.resourceNum > 0 && item.price > 0 ||item&&item.name==='Dropbox BI Package'||item&&item.name==='OneDrive BI Package'})
}

export const handleBot = async (data) => {
  return filter(data, { type: 3 })
}

export const handleBundle = async (data) => {
  const ids = find(filter(data, { type: 0 }), { name: 'STARTUP' })
  const { data: ruleDetail } = await pay.rules({ ids: ids.appId })
  const ruleObj = find(ruleDetail.data, { appId: ids.appId, type: 9 })
  return filter(data, { type: 0 }).map(item => {
    item.intelligenceNumber = ruleObj ? Number(ruleObj.threshold.value) : null
    return item
  })
}

export const handleApps = async (data) => {
  const arr = filter(data, { type: 1 })
  return filter(arr, (item) => { return item.price && item.price > 0 })
}
